package com.ebring.shareEducation.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @Date 2018/7/18
 * @Description html转pdf
 */
public class Pdfutils {


    /**
     *
     *根据用户输入的信息
     *创建生成pdf文件
     *
     * @param editor 教师输入的备课信息
     * */

    public static String creatpdf(String editor) throws IOException, DocumentException {

        String fileNum = UUID.randomUUID().toString().replace("-","");
        String fileUrl = "E:\\pdf\\" + fileNum + ".pdf";//设置导出路径
        //String fileUrl = "192.168.108.237:8080/opt/pic";
        OutputStream os = new FileOutputStream(fileUrl);
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver font = renderer.getFontResolver();
        font.addFont("C:/WINDOWS/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//添加中文识别，这里是设置的宋体，Linux下要换成对应的字体
        StringBuffer html = new StringBuffer();
        // DOCTYPE 必需写否则类似于 这样的字符解析会出现错误
        html.append("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN/' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
        html.append("<html xmlns='http://www.w3.org/1999/xhtml'>");
        html.append("<head><link rel='stylesheet' type='text/css' href='https://mipcache.bdstatic.com/static/v1/mip.css'/><style>body{font-family:SimSun;font-size:14px;}</style> ");//此处一定要加，不然字体也不会显示，不要加line-height属性
        html.append("<title>" + "课件PDF" + "</title>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div>" + editor + "</div>");//这里根据实际情况替换成你的HTML代码就OK了
        html.append("</body></html>");

        renderer.setDocumentFromString(html.toString());
        renderer.createPDF(os);
        renderer.finishPDF();
        return "http://192.168.108.245:8100/pdf/"+fileNum;
    }
}
